package com.ytxg.health_management.webSocket;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.ytxg.health_management.webSocket.entity.WebSocketMessage;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint("/api/webSocket/{id}")
@Component
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    private static final Map<Integer, Session> userSessions = new ConcurrentHashMap<>();
    private int userId;


    @OnOpen
    public void onOpen(Session session, @PathParam("id") int userId) {
        this.userId = userId;
        userSessions.put(userId,session);
        log.info("链接成功 user: {}", this.userId);
    }

    @OnMessage
    public void onMessage(String message, Session session) {

    }


    @OnClose
    public void onClose() {
        userSessions.remove(this.userId);
        log.info("链接关闭 user: {}", this.userId);
    }

    public static void sendMessageToUser(int userId, WebSocketMessage<Object> message) {
        Session session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                session.getBasicRemote().sendText(objectMapper.writeValueAsString(message));
            } catch (IOException e) {
                log.info("发送消息失败 user: {}", userId);
            }
        }
    }
    public static void sendMessageToAll(WebSocketMessage<Object> message) {
        for (Session session : userSessions.values()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                session.getBasicRemote().sendText(objectMapper.writeValueAsString(message));
            } catch (IOException e) {
                log.info("群体信息发送失败");
            }
        }
    }

}
